package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.*;
import com.zzyl.serve.mapper.*;
import com.zzyl.serve.vo.CheckInConfigVo;
import com.zzyl.serve.vo.CheckInDetailVo;
import com.zzyl.serve.vo.CheckInElderVo;
import com.zzyl.serve.vo.ElderFamilyVo;
import net.sf.jsqlparser.statement.create.table.CheckConstraint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-15
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;
    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void apply(CheckInApplyDto dto) {
        //1.老人表插入

        //1.1 判断老人是否以及入住,如果老人已经入住（老人身份证号已存在，且状态为1），则抛异常
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        String idCardNo = checkInElderDto.getIdCardNo();
        //通过身份证查找老人
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,idCardNo);
        Elder elder = elderMapper.selectOne(wrapper);
        if(elder !=null && Objects.equals(elder.getStatus(),1)){
            throw new BaseException("该老人已入住");
        }
        //1.2 更新床位状态为“已入住”（如果床位是未入住时才允许入住）
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = bedMapper.selectBedById(bedId);
        if(Objects.equals(bed.getBedStatus(),1)){
            throw new BaseException("该床位已经有人入住了");
        }
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);
        //1.3 保存老人表(如果表中有老人的信息，则为更新，否则为新增)
        Elder elderToDB = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elderToDB);
        elderToDB.setStatus(1);
        elderToDB.setBedNumber(bed.getBedNumber());
        elderToDB.setBedId(bedId);
        //1.4家属信息转化为字符串存到remark里面
        List<ElderFamilyDto> familyDtoList = dto.getElderFamilyDtoList();
        elderToDB.setRemark(JSONUtil.toJsonStr(familyDtoList));

        if(elder == null){
            elderMapper.insertElder(elderToDB);
        }else{
            elderToDB.setId(elder.getId());
            elderMapper.updateElder(elderToDB);
        }



        //2.新增入住信息
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckIn checkin = new CheckIn();
        checkin.setElderName(elderToDB.getName());
        checkin.setElderId(elderToDB.getId());
        checkin.setIdCardNo(elderToDB.getIdCardNo());
        checkin.setStartDate(checkInConfigDto.getStartDate());
        checkin.setEndDate(checkInConfigDto.getEndDate());
        checkin.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkin.setBedNumber(bed.getBedNumber());
        checkin.setStatus(0);
        save(checkin);

        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkin.getId());
        checkInConfigMapper.insert(checkInConfig);

        //3.签约信息新增
        Contract contract = new Contract();
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setElderId(elderToDB.getId());
        contract.setElderName(elderToDB.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        //  如果当前时间 不早于合同开始时间，且不晚于合同结束时间，说明在合同有效期内
        LocalDateTime now = LocalDateTime.now();
        boolean beInForce = !now.isBefore(contract.getStartDate()) && !now.isAfter(contract.getEndDate());
        contract.setStatus(beInForce?1:0);
        contractMapper.insert(contract);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public CheckInDetailVo checkInDetailById(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectElderById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
//        checkInElderVo.setId(elder.getId());
//        checkInElderVo.setName(elder.getName());
//        checkInElderVo.setIdCardNo(elder.getIdCardNo());
//        checkInElderVo.setBirthday(elder.getBirthday());
//        checkInElderVo.setSex(elder.getSex());
//        checkInElderVo.setPhone(elder.getPhone());
//        checkInElderVo.setAddress(elder.getAddress());
//        checkInElderVo.setImage(elder.getImage());
//        checkInElderVo.setIdCardNationalEmblemImg(elder.getIdCardNationalEmblemImg());
//        checkInElderVo.setImage(elder.getImage());

           BeanUtils.copyProperties(elder,checkInElderVo);
           checkInElderVo.setAge(IDCardUtils.getAgeByIdCard(elder.getIdCardNo()));
           vo.setCheckInElderVo(checkInElderVo);

           String remark = elder.getRemark();
           //字符串转化为elderFamilyVo的list
           List<ElderFamilyVo> familyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
           vo.setElderFamilyVoList(familyVoList);

           CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
           CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigByCheckInid(id);
           BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
           checkInConfigVo.setStartDate(checkIn.getStartDate());
           checkInConfigVo.setEndDate(checkIn.getEndDate());
           checkInConfigVo.setBedNumber(checkIn.getBedNumber());
           vo.setCheckInConfigVo(checkInConfigVo);

           Contract contract = contractMapper.selectContractByElderId(elderId);
           vo.setContract(contract);


        return vo;
    }


}
